<template>
  <div id="Caigou">
    <h3>采购单申请</h3>
    <!--操作按钮开始-->
    <el-row>
      <el-col :span="9" :offset="14">
        <el-button type="primary" @click="showCommodityList">添加商品</el-button>
        <el-button type="danger" @click="handleRemove">移除商品</el-button>
        <el-button type="success" @click="onSubmit">提交</el-button>
      </el-col>
    </el-row>
    <!--操作按钮结束-->
    <!--采购单明细表格开始-->
    <el-table :data="procedureDetails" stripe
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column label="序号">
        <template #default="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="商品名称" prop="commodityName">
      </el-table-column>
      <el-table-column label="供货商名称" prop="vendorName">
      </el-table-column>
      <el-table-column label="单价" prop="price">
      </el-table-column>
      <!--            <el-table-column label="数量" prop="count">-->
      <!--                <template #default="scope">-->
      <!--                    <el-input-number v-model="scope.row.count"-->
      <!--                                     :min="1"></el-input-number>-->
      <!--                </template>-->
      <!--            </el-table-column>-->

      <el-table-column label="数量" prop="count">
        <template #default="scope">
          <el-input-number
              v-model="scope.row.count"
              :min="1"
              @change="calculateSubtotal(scope.row)"> <!-- 监听变化 -->
          </el-input-number>
        </template>
      </el-table-column>

      <el-table-column prop="subtotal" label="小计">
      </el-table-column>
    </el-table>

    <!--采购单明细表格结束-->
    <!--采购表单其它项-->
    <el-form v-model="form" label-width="80px" style="margin: 30px 100px;">
      <el-row>
        <el-col :span="12">
          <el-form-item label="总数量">
            <el-input v-model="form.procureCount" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总金额">
            <el-input v-model="form.procurePrice" readonly>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input type="textarea" v-model="form.procureRemark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!--采购表单其它项-->
    </el-form>


    <!--展示商品列表对话框开始-->
    <el-dialog title="全部商品" :visible.sync="dialogFormVisible">
      <el-table
          :data="tableData"
          border
          style="width: 100%">
        <el-table-column
            fixed
            prop="commodityId"
            label="商品编号"
            width="100">
        </el-table-column>
<!--        <el-table-column-->
<!--            prop="image"-->
<!--            label="商品图片"-->
<!--            width="100">-->
<!--          <template slot-scope="scoped">-->
<!--            <el-image style="width: 50px;height: 50px" :src="scoped.row.productImage.image"></el-image>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column
            prop="commodityName"
            label="商品名称"
            width="100">
        </el-table-column>
        <el-table-column
            prop="commodityPrice"
            label="商品价格"
            width="100">
        </el-table-column>
        <el-table-column
            label="上架状态"
            width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0">{{ scope.row.status == 0 ? '上架':'下架' }}</el-tag>
            <el-tag v-else type="danger">{{ scope.row.status == 0 ? '上架':'下架' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作">
          <template slot-scope="scope">
            <el-button @click="searchPurchase(scope.row)" type="text" size="small">查看供货商</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="current"
          :page-sizes="sizeList"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-dialog>
    <!--展示商品列表对话框结束-->

    <!--选择供货商的界面开始-->
    <el-dialog title="供货商报价" :visible.sync="dialogTableVisible2">
      <el-tag style="margin-left: 0px;" v-if="quoteList.length==0">暂无供货商报价</el-tag>
      <div v-else>
        <el-tag>
          商品名称：{{quoteList[0].commodityName}}
          基础价格：{{quoteList[0].commodityPrice}}
        </el-tag>
        <el-table :data="quoteList">
          <el-table-column prop="userName" label="供货商" width="200"></el-table-column>
          <!--头像-->
          <el-table-column prop="userAvatar" label="头像">
            <template slot-scope="scope">
              <el-image style="width: 50px;height: 50px" :src="scope.row.userAvatar"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="productOffer" label="价格"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="choose(scope.row)" type="text" size="small">选择</el-button>
            </template>
          </el-table-column>

        </el-table>

      </div>
    </el-dialog>

    <!--选择供货商的界面结束-->
  </div>
</template>

<script>
export default{
  name: 'Caigou',
  data(){
    return{
      // 所有采购项明细的数组
      procedureDetails: [],
      // 展示全部商品的对话框
      dialogFormVisible: false,
      // 全部商品表格绑定的数组
      tableData:[],
      current: 1,
      size: 2,
      sizeList: [2, 4, 6, 8],
      total: 0,
// 供货商报价列表
      quoteList:[],
      current6: 1,
      size6: 10,
      sizeList6: [10, 20, 30, 40],
      total6: 0,
      // 供货商报价界面对话框显示
      dialogTableVisible2: false,
      // 表单绑定的对象
      form: {
        procureRemark: '',
        procureId:'',
        procurePrice:0,
        procureCount:0,
      },

    }
  },
  methods: {
    //计算小计
    calculateSubtotal(row) {
      row.subtotal = row.price * row.count; // 小计 = 单价 × 数量
      this.updateTotals(); // 更新总金额
    },

    // 更新总数量和总金额
    updateTotals() {
      let procurePrice = 0;
      let procureCount = 0;

      this.procedureDetails.forEach(item => {
        procureCount += item.count;
        procurePrice += item.price * item.count;
      });

      this.form.procureCount = procureCount;
      this.form.procurePrice = procurePrice.toFixed(2);
    },
    // 提交按钮
    onSubmit() {
      // alert('this.form.procurePrice',this.form.procurePrice)
      // console.log('this.form.procurePrice',this.form.procurePrice)
      // 确保总金额是最新的
      this.updateTotals();
      // 将表格中的数据加入到当前对象中
       this.form.details = this.procedureDetails
      this.form.details = [];
      this.procedureDetails.forEach(item => {
        this.form.details.push({
          ...item,
          subtotal: item.price * item.count
        });
      });
      console.log('form', this.form)
      let sysUser = JSON.parse(sessionStorage.getItem('uid6'));
      this.form.procureId = sysUser

      console.log('this.form.procureId',this.form.procureId)
      console.log('this.form',this.form)


      // 发送请求到后端，执行插入，
      this.$axios.post(`/Commodity/procureProcureDetailsAdd`, this.form).then(res => {
        if(res.data == "success")
          this.$message.success('采购单申请提交成功')
        this.$router.push('/ProcureShenHe')

      })
    },

    // 表格复选框选中改变事件
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 添加商品
    showCommodityList() {
      // 展示全部商品的对话框要显示
      this.dialogFormVisible = true
      this.getCommidityList()
    },
    // 获取所有商品列表
    getCommidityList() {
      // 获取全部商品
      this.$axios.post(`/Commodity/selectAll/${this.current}/${this.size}`, {})
          .then(res => {
            console.log('商品列表', res.data)
            console.log('商品列表', res.data.rows)
            // 把商品列表绑定到表格中
            this.tableData = res.data.rows
            this.total = res.data.total
          })
    },
    // 移除商品
    handleRemove() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.$confirm('确定要移除选中的商品吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 过滤掉选中的商品
          this.procedureDetails = this.procedureDetails.filter(item =>
              !this.multipleSelection.some(selected => selected.commodityId === item.commodityId && selected.vendorId === item.vendorId)
          );
          this.updateTotals(); // 移除商品后更新总数
          this.$message({
            type: 'success',
            message: '移除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消移除'
          });
        });
      } else {
        this.$message.warning('请至少选择一条要移除的数据');
      }
    },
    // 查看供货商
    searchPurchase(val) {
      console.log(123,val)
      this.dialogTableVisible2 = true
      this.$axios.get(`/Commodity/selectPrice/${this.current6}/${this.size6}?id=${val.id}`)
          .then(res => {
            console.log('供货商报价列表', res.data)
            this.quoteList = res.data.rows
            this.total6 = res.data.total
            console.log(11,this.quoteList)
          })
    },
    //添加数量变化时自动计算小计

    // 页大小改变

    handleSizeChange(val) {
      this.size = val
      this.getCommidityList()
    },
    // 页号改变

    handleCurrentChange(val) {
      this.current = val
      this.getCommidityList()
    },
    // 选择供货商
    choose(val) {
      // 重新封装采购项明细对象
      let detail = {
        "vendorId": val.id,
        "commodityName": val.commodityName,
        "vendorName": val.userName,
        "commodityId": val.id,
        "price": val.productOffer,
        "count": 1,
        "subtotal": val.productOffer * 1,
      }

      // 思路：根据要添加的当前采购项的商品id和供货商id，判断是否已经在已有的采购明细数组中存在
      // 如果不存在，直接加入对象
      // 如果存在，提示不能加入已存在的数据
      const ary = this.procedureDetails.filter(item => {
        return (item.commodityId === detail.commodityId
            && item.vendorId === detail.vendorId)
      })

      if(ary.length == 0)
        this.procedureDetails.push(detail)
      else
        this.$message.error('相同的报价不能重复添加')
    }
  },
  created() {
  },

}
</script>
